"""
$Id: SQLLogMiddleware.py 251 2007-07-27 12:17:19Z tguettler $

This middleware 
in settings.py you need to set

DEBUG=True
SQL_DEBUG=True

MIDDLEWARE_CLASSES = (
    'YOURPATH.SQLLogMiddleware.SQLLogMiddleware',
    'django.middleware.transaction.TransactionMiddleware',
    ...)

"""

# Python
import time

# Django
from django.conf import settings
from django.db import connection
from django.template import Template, Context

class SQLLogMiddleware:

    start=None

    def process_request(self, request):
        self.start=time.time()

    def process_response (self, request, response):
        # self.start is empty if a append slash redirect happened.
        if (not self.start) or not (settings.DEBUG and
                getattr(settings, "SQL_DEBUG", False) and
        response.__getitem__("Content-Type").startswith("text/html")):
                #response.headers.get("Content-Type", "").startswith("text/html")):
            self.start=None
            return response
        timesql=0.0
        for q in connection.queries:
            timesql+=float(q['time'])
        seen={}
        duplicate=0
        for q in connection.queries:
            sql=q["sql"]
            c=seen.get(sql, 0)
            if c:
                duplicate+=1
            q["seen"]=c
            seen[sql]=c+1
            
        t = Template('''
            <p>
             <em>Total query count:</em> {{ queries|length }}<br/>
             <em>Total duplicate query count:</em> {{ duplicate }}<br/>
             <em>Total SQL execution time:</em> {{ timesql }}<br/>
             <em>Total Request execution time:</em> {{ timerequest }}<br/>
            </p>
            <table class="sqllog">
             <tr>
              <th>Time</th>
              <th>Seen</th>
              <th>SQL</th>
             </tr> 
                {% for sql in queries %}
                    <tr>
                     <td>{{ sql.time }}</td>
                     <td align="right">{{ sql.seen }}</td>
                     <td>{{ sql.sql }}</td>
                    </tr> 
                {% endfor %}
            </table>
        ''')
        timerequest=round(time.time()-self.start, 3)
        queries=connection.queries
        response.write(t.render(Context(locals())))
        self.start=None
        return response

